package com.fatcat.easybuy.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.UUID;

/**
 * @author 郝秦毅
 * @since 2025/9/12 14:30
 */
public class JwtUtil {
    //过期时间
    private static final long EXPIRE = 1000 * 60 * 60 * 24;
    //秘钥
    private static final String SECRET = "9508827a6c9211a4178d1f0b9a4f597a6e70d1f409951f9a4741a6b13e3b1efb";

    //生成Token
    public static String createToken(long UserId) {
        Date lastTime = new Date();//当前时间
        Date expireTime = new Date(lastTime.getTime() + EXPIRE);//过期时间

        //生成Token
        String Token = JWT.create()//创建JWT
                .withJWTId(UUID.randomUUID().toString())//JWTID
                .withIssuedAt(lastTime)//签发时间
                .withExpiresAt(expireTime)//过期时间
                .withClaim("UserId", UserId)//用户id
                .sign(Algorithm.HMAC256(SECRET));//签名
        return Token;
    }

    //验证Token有效性
    public static DecodedJWT verifyToken(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }


    //从Token中获取用户id
    public static long getUserId(String token) {
        DecodedJWT decodedJWT = verifyToken(token);
        return decodedJWT.getClaim("UserId").asLong();
    }

    //从Token中获取过期时间
    public static Date getExpireTime(String token) {
        DecodedJWT decodedJWT = verifyToken(token);
        return decodedJWT.getExpiresAt();
    }
}
